<template>
    <DialogComponent class="custom-dialog" :layer="dialogParams" @update:visible="closeAcountDialog" @confirm="confirmAcountDialog">
        <div>
            <div class="notice">请谨慎批量操作；请确认后再点击确认批量增加角色</div>
            <div class="selected-role-box" v-if="!props.isMultiple">
                <span>已选 {{multipleSelection?.length}} 个角色：</span>
                <div class="selected-num">
                    <span v-for="(item, key) in multipleSelection" :key="key" class="selected-role">
                        <el-tag class="ml-2" type="info" closable @close="del(item, key)">
                            {{item.roleName}}
                            <el-tooltip
                                class="box-item"
                                effect="dark"
                                :content="item.comments"
                                placement="top-start"
                            >
                                <el-icon v-show="item.comments"><QuestionFilled /></el-icon>
                            </el-tooltip>
                        </el-tag>
                    </span>
                </div>
                <!-- <div class="selected-show-more"><span v-show="!showMore" @click="showMore=!showMore"><el-icon><ArrowDown /></el-icon>展开</span><span v-show="showMore" @click="showMore=!showMore"><el-icon><ArrowUp /></el-icon>收起</span></div> -->
            </div>
            <div class="users" v-else>已选 {{props.userList.length}} 个用户</div>
            <el-row class="mt20">
                <el-col :span="24">
                    <el-input v-model.trim="requestData.keyword" @change="serach" placeholder="请输入角色关键词" size="large" maxlength="200" :suffix-icon="Search" class="search-input float-right" clearable/>
                </el-col>
            </el-row>
            <TableWrap hideHeader title="用户列表" :total="total"
                :loading="loading" v-model:pageSize="requestData.pageSize" :noSelection="false"
                v-model:pageIndex="requestData.pageIndex" :tableData="tableData" @request-list="getList" class="mt20">
                    <el-table
                        ref="multipleTable"
                        :data="tableData"
                        style="width: 100%"
                        :row-key="getRowKeys"
                    >
                        <!-- <el-table-column v-if="!props.isMultiple" type="selection" width="55" :reserve-selection="true"/> -->
                        <el-table-column v-if="!props.isMultiple"  width="55">
                            <template #header>
                                <el-checkbox name="all" v-model="checkedAll" @change="selectAll"><span></span></el-checkbox>
                            </template>
                            <template #default="scope">
                                <el-checkbox name="single" v-model="scope.row.selected" @change="select(scope.row, scope.row.selected)"><span></span></el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column label="选择" width="80" v-else>
                            <template #default="scope">
                                <el-radio name="application" :label="scope.row.roleCode" v-model="checkedValue" @change="handleCurrentChange(scope.row)"><span></span></el-radio>
                            </template>
                        </el-table-column>
                        <el-table-column prop="roleName" min-width="140" label="角色名称" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="roleCode" min-width="140" label="角色代码" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="comments" min-width="140" label="角色描述" show-overflow-tooltip></el-table-column>
                    </el-table>
            </TableWrap>
        </div>
    </DialogComponent>
</template>
<script>
import { ref, reactive, toRefs, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import DialogComponent from '@/components/dialogComp.vue'
import TableWrap from '@/components/table-wrap/table-wrap.vue'
import { Search, QuestionFilled, ArrowUp, ArrowDown, MuteNotification } from '@element-plus/icons-vue'
import {messageError, messageSuccess} from '@/hooks/useMessage'
export default {
    components: { DialogComponent, TableWrap, QuestionFilled },
    props: {
        // 用户id数组
        userList: {
            type: Array,
            default: () => []
        },
        // 是不是多选的用户
        isMultiple: {
            type: Boolean,
            default: false
        },
        // 组织id
        institutionId: {
            type: [String, Number],
            default: ''
        },
        // 用户类型 1中台 2组织
        type: {
            type: [String, Number],
            default: 1
        },
        dialogParams: {
            type: Object,
            default: () => {
                return {}
            },
            required: true
        },
        account: {
            type: Object,
            default: () => {
                return null
            }
        }
    },
    emits: ['dialog:confirm', 'dialog:close'],
    setup(props, ctx) {
        const store = useStore()
        const { account } = toRefs(props)
        console.log('account', account)
        let showMore = ref(false)
        const multipleTable = ref()
        const keyword = ref('')
        const tableData = ref([{
            id: 1001,
            name: '张三',
            username: 'zhangsan'
        }]);
        const total = ref(0);
        const loading = ref(false)
        const requestData = ref({
            pageIndex: 1,
            pageSize: 10,
            keyword: ''
        });
        // 批量操作时的表格单选项
        let checkedValue = ref(false)
        const multipleSelection = ref([])
        const checkedAll = ref(false)
        // 多选行
        const handleSelectionChange = (selection) => {
            console.log('selection', selection)
            multipleSelection.value = selection
        }
        const isCkeckAll = (data) => {
            let isAllCkecked = true
            data.forEach((item) => {
                if(!item.selected) {
                    isAllCkecked = false
                }
            })
            return isAllCkecked
        }
        const select = (row, checked) => {
            console.log('selection row', checked, row)
            if(checked) {
                if(!selectedRole[row.rid]) {
                    selectedRole[row.rid] = row
                    multipleSelection.value.push(row)
                    checkedAll.value = isCkeckAll(tableData.value)
                }
            } else {
                checkedAll.value = false
                if(selectedRole[row.rid]) {
                    delete selectedRole[row.rid]
                    multipleSelection.value = multipleSelection.value.filter((value) => {
                        return value.rid !== row.rid
                    })
                }
            }
        }
        const selectAll = (checked) => {
            console.log('selection all', checked)
            tableData.value.forEach((item) => {
                item.selected = checked
                if(checked) {
                    if(!selectedRole[item.rid]) {
                        selectedRole[item.rid] = item
                        multipleSelection.value.push(item)
                    }
                } else {
                    if(selectedRole[item.rid]) {
                        delete selectedRole[item.rid]
                        multipleSelection.value = multipleSelection.value.filter((value) => {
                            return value.rid !== item.rid
                        })
                    }
                }
                
            })
        }
        // 选中当前行
        const handleCurrentChange = (cur) => {
            console.log(cur)
            multipleSelection.value = cur && [cur] || []
        }
        const getRowKeys = (row) => {
            let rid = row.id || row.roleId
            return rid;
        }
        const selectedRole = {}
        // 已分配的角色列表
        const getUserSystemRoles = () => {
            let api = props.type == 1 ? 'wandGetUserSystemRoles' : 'getUserRoles'
            let params = props.type == 1
            ? {userId: account.value.userId}
            : {institutionId: props.institutionId, memberId: account.value.memberId}
            store.dispatch('proxyAction', {
                name: api,
                queries: params
            }).then((res) => {
                res.data && res.data.forEach(function(item) {
                    item.rid = item.id ? item.id : item.roleId
                    selectedRole[item.rid] = item
                })
                multipleSelection.value = res.data
                getList()
                nextTick(() => { 
                    toggleSelection(res.data)
                })
            })
        }
        // 列表
        const getList = () => {
            console.log('keyword', account.value.memberId)
            loading.value = true;
            let api = props.type == 1 ? 'wandGetUserRolesList' : 'assignRoleList'
            let params = props.type == 1
            ? {userId: account.value.userId, clientChannelCode: 5}
            : {institutionId: props.institutionId, memberId: account.value.memberId}
            // const {name='', institutionName='', expertise=''} = filterParams.value

            store.dispatch('proxyAction', {
                name: api,
                data: props.type == 1 ? { ...requestData.value, ...params, enabled: 1 } : null,
                queries: props.type == 2 ? { ...requestData.value, ...params } : null
            }).then((res) => {
                if(res&&res.data) {
                    tableData.value = res.data.rows.map(item => ({...item, rid: item.id ? item.id : item.roleId, selected: !!selectedRole[item.id]||!!selectedRole[item.roleId]})) || [];
                    total.value = res.data.total;
                    checkedAll.value = isCkeckAll(tableData.value)
                }
            }).finally(() => {
                loading.value = false;
            })
        }
        const serach = () => {
            requestData.value.pageIndex = 1
            getList()
        }
        // 批量分配角色
        const setUsersRole = function(){
            console.log(multipleSelection.value, 123)
            store.dispatch('proxyAction', {
                name: 'assginSomeUserRole',
                data: {
                    memberIds: props.userList,
                    roleCode: multipleSelection.value[0].roleCode,
                    institutionId: props.institutionId
                }
            }).then((res) => {
                ctx.emit('dialog:confirm')
            })
        }
        // 分配角色
        const assignRoles = function(roleIds) {
            let api = props.type == 1 ? 'wandAssignRoles' : 'assginUserRole'
            let params = props.type == 1
            ? {userId: account.value.userId, roleIds}
            : {institutionRoleList: roleIds, memberId: account.value.memberId}
            store.dispatch('proxyAction', {
                name: api,
                data: params
            }).then((res) => {
                ctx.emit('dialog:confirm')
            })
        }
        // 关闭添加账号对话框
        const closeAcountDialog = () => {
            console.log('dialogParams', props.dialogParams.value)
            // props.dialogParams.value.show = false;
            ctx.emit('dialog:close')
        }
        // 账号对话框confirm
        const confirmAcountDialog = () => {
            if(multipleSelection.value.length == 0) {
                store.dispatch('message', {
                    message: '请先选择角色',
                    type: 'error'
                })
                return 
            }
            if(!props.isMultiple){ // 单独用户分配角色
               let roleIds = []
                if(props.type == 1){ // 中台用户角色
                    multipleSelection.value.forEach(function(item) {
                        roleIds.push(item.id)
                    })
                }else{ // 组织用户角色
                    const roleModels = multipleSelection.value.map(item => {
                        return {
                            roleCode: item.roleCode,
                            roleId: item.roleId,
                            roleName: item.roleName
                        }
                    })
                    roleIds = [{institutionId: props.institutionId, roleModels}]
                }
                assignRoles(roleIds) 
            }else{ // 批量用户分配角色
                setUsersRole()
            }
            // props.dialogParams.value.show = false;
            // ctx.emit('dialog:confirm')
        }
        const del = (item, index) => {
            console.log('index', index)
            if(selectedRole[item.rid]) {
                delete selectedRole[item.rid]
            }
            multipleSelection.value.splice(index, 1)
            tableData.value.forEach((value) => {
                if(value.rid === item.rid) {
                    value.selected = false
                    checkedAll.value = false
                }
            })
            
        }
        const toggleSelection = (rows) => {
            if (rows) {
                rows.forEach((row) => {
                    selectedRole[row.rid]&&multipleTable.value.toggleRowSelection(row, true)
                })
            }
        }
        onMounted(() => {
            if(!props.isMultiple){
                getUserSystemRoles()
            }else{
                getList()
            }
        })
        return {
            checkedValue,
            handleCurrentChange,
            props,
            Search,
            showMore,
            keyword,
            multipleTable,
            tableData,
            total,
            loading,
            requestData,
            multipleSelection,
            handleSelectionChange,
            checkedAll,
            select,
            selectAll,
            getList,
            serach,
            getRowKeys,
            closeAcountDialog,
            confirmAcountDialog,
            del
        };
    }
}
</script>
<style lang="scss" scoped>
.w200 {
    width: 200px;
}
.mr0 {
    margin-right: 0;
}
.mt20 {
    margin-top: 20px;
}
.search-input {
    width: 270px;
}
.selected-role-box {
    display: flex;
    .selected-num {
        max-height: 100px;
        flex: 1;
        overflow: auto;
        &.showMore {
            max-height: 100px;
            overflow-y: auto;
        }
    }
    .selected-show-more {
        margin-left: 10px;
    }
}
.selected-role {
    display: inline-block;
    margin-left: 10px;
    margin-bottom: 10px;
}
.notice {
    color: var(--el-color-warning);
    margin-bottom: 20px;
}
</style>